let _Vue = null;

export default class VueRouter {
  static install(Vue) {
    //判断是否已经被安装
    if (VueRouter.install.installed) {
      return;
    }
    VueRouter.install.installed = true;
    // Vue构造函数记录到全局变量中
    _Vue = Vue;
    //  把创建Vue实例时候传入的router对象注入到Vue实例上
    _Vue.mixin({
      beforeCreate() { 
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router;
          this.$options.router.init()
        }
      }
    });
  }
  constructor(options) {
    console.log(options)
    this.options = options
    this.routeMap = {}
    // observable
    this.data = _Vue.observable({
        current: window.location.hash.replace("#", "") || "/"
    })
 
    this.init()
  }

  init(){
      this.createRouteMap()
      this.initComponents(_Vue)
      this.initEvent()
  }

   //遍历所有路由规则,解析成键值对的形式存储到routerMap对象中
  createRouteMap() {  
    this.options.routes.forEach(route => { 
      this.routeMap[route.path] = route.component;
    });
  }
  //创建组件
  initComponents(Vue) {
    Vue.component("router-link",{
      props:{//接收参数
          to:String
      },
      render(h){
        return h('a',{
          attrs:{
            href:this.to
          },
          on:{
            click:this.clickHandler
          }
        },[this.$slots.default])
      },
      methods:{
        clickHandler(e){
          window.location.hash = this.to;
          this.$router.data.current=this.to
          e.preventDefault()
        }
      }
      //slot 插槽占位 替换变化的内容
      // template:"<a :href='to'><slot></slot></a>"
    });
    const self=this
    Vue.component('router-view',{
      render(h){
        const component=self.routeMap[self.data.current]
        return h(component)
      }
    })
  }
  initEvent(){
    window.addEventListener('hashchange',()=>{ 
      console.log(window.location.hash)
      this.data.current=window.location.hash.replace('#', '')
    })
  }
}
